package com.hbk.base.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MyPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        if(bean instanceof DataSourceProperties){
            DataSourceProperties p = (DataSourceProperties) bean;
            changeMySQL(p);
        }
        if(bean instanceof RedisProperties){
            RedisProperties p = (RedisProperties) bean;
            changeRedis(p);
        }

        return bean;
    }

    private void changeMySQL(DataSourceProperties p) {
        ExternalConfig.MysqlConfig mysqlConfig = EnvPostProcessor.getExternalConfig().getMysql();
        // jdbc:mysql://localhost:3306/hbk01?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Hongkong
        StringBuilder builder = new StringBuilder();
        builder.append("jdbc:mysql://");
        builder.append(mysqlConfig.getHost());
        builder.append(":");
        builder.append(mysqlConfig.getPort());
        builder.append("/");
        builder.append(mysqlConfig.getDatabase());
        builder.append("?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Hongkong");
        String url = builder.toString();
        p.setUrl(url);
        p.setUsername(mysqlConfig.getUsername());
        p.setPassword(mysqlConfig.getPassword());
        log.info("reset mysql config success");
    }

    private void changeRedis(RedisProperties p) {
        ExternalConfig.RedisConfig redisConfig = EnvPostProcessor.getExternalConfig().getRedis();
        p.setHost(redisConfig.getHost());
        p.setPort(redisConfig.getPort());
        p.setPassword(redisConfig.getPassword());
        p.setDatabase(redisConfig.getDataIndex());
        log.info("reset redis config success");
    }
}
